<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>柜门管理 - MQTT服务器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: white;
            border-radius: 15px;
            padding: 25px 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .door-icon {
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 24px;
        }
        
        .header-info h1 {
            color: #4a5568;
            font-size: 2.2em;
            margin-bottom: 5px;
        }
        
        .header-info p {
            color: #718096;
            font-size: 1.1em;
        }
        
        .back-btn {
            background: #e2e8f0;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1em;
            font-weight: 600;
            color: #4a5568;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .back-btn:hover {
            background: #cbd5e0;
            transform: translateY(-2px);
        }
        
        .controls-bar {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .control-btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.9em;
            font-weight: 600;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .open-all-btn {
            background: #48bb78;
            color: white;
        }
        
        .open-all-btn:hover {
            background: #38a169;
            transform: translateY(-2px);
        }
        
        .clear-all-btn {
            background: #f56565;
            color: white;
        }
        
        .clear-all-btn:hover {
            background: #e53e3e;
            transform: translateY(-2px);
        }
        
        .refresh-btn {
            background: #4299e1;
            color: white;
        }
        
        .refresh-btn:hover {
            background: #3182ce;
            transform: translateY(-2px);
        }
        
        .filter-select {
            padding: 8px 12px;
            border: 2px solid #e2e8f0;
            border-radius: 6px;
            font-size: 0.9em;
            background: white;
        }
        
        .door-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
        }
        
        .door-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .door-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
        }
        
        .door-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: var(--status-color);
        }
        
        .door-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .door-number {
            font-size: 1.3em;
            font-weight: bold;
            color: #2d3748;
        }
        
        .door-status {
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 0.8em;
            font-weight: 600;
        }
        
        .status-available { 
            background: #c6f6d5; 
            color: #22543d; 
            --status-color: #48bb78;
        }
        
        .status-occupied { 
            background: #fed7d7; 
            color: #742a2a; 
            --status-color: #f56565;
        }
        
        .status-open { 
            background: #bee3f8; 
            color: #2a4365; 
            --status-color: #4299e1;
        }
        
        .door-info {
            margin-bottom: 15px;
        }
        
        .door-info-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 0.9em;
        }
        
        .door-info-label {
            color: #718096;
        }
        
        .door-info-value {
            color: #2d3748;
            font-weight: 500;
        }
        
        .door-actions {
            display: flex;
            gap: 8px;
        }
        
        .action-btn {
            flex: 1;
            padding: 8px 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.85em;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .open-btn {
            background: #48bb78;
            color: white;
        }
        
        .open-btn:hover {
            background: #38a169;
        }
        
        .clear-btn {
            background: #f56565;
            color: white;
        }
        
        .clear-btn:hover {
            background: #e53e3e;
        }
        
        .edit-btn {
            background: #4299e1;
            color: white;
        }
        
        .edit-btn:hover {
            background: #3182ce;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #718096;
        }
        
        .loading::after {
            content: '';
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #e2e8f0;
            border-top: 2px solid #4299e1;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-left: 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .stats-bar {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 25px;
        }
        
        .stat-card {
            background: white;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            box-shadow: 0 3px 10px rgba(0,0,0,0.05);
        }
        
        .stat-number {
            font-size: 2em;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .stat-label {
            color: #718096;
            font-size: 0.85em;
        }
        
        .command-log {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-top: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            max-height: 300px;
            overflow-y: auto;
        }
        
        .command-log h3 {
            margin-bottom: 15px;
            color: #2d3748;
        }
        
        .command-item {
            padding: 10px;
            background: #f7fafc;
            border-radius: 6px;
            margin-bottom: 8px;
            font-family: 'Courier New', monospace;
            font-size: 0.85em;
        }
        
        .command-time {
            color: #718096;
            margin-right: 10px;
        }
        
        @media (max-width: 768px) {
            .header {
                flex-direction: column;
                gap: 15px;
            }
            
            .controls-bar {
                flex-direction: column;
                align-items: stretch;
            }
            
            .door-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 头部 -->
        <div class="header">
            <div class="header-left">
                <div class="door-icon">🚪</div>
                <div class="header-info">
                    <h1>柜门管理</h1>
                    <p id="deviceName">HarmonyOS设备1 - 实时控制</p>
                </div>
            </div>
            <button class="back-btn" onclick="goBack()">
                ← 返回设备管理
            </button>
        </div>
        
        <!-- 统计信息 -->
        <div class="stats-bar">
            <div class="stat-card">
                <div class="stat-number" style="color: #48bb78;" id="availableCount">0</div>
                <div class="stat-label">可用柜门</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" style="color: #f56565;" id="occupiedCount">0</div>
                <div class="stat-label">已使用</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" style="color: #4299e1;" id="openCount">0</div>
                <div class="stat-label">开启中</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" style="color: #9f7aea;" id="totalCount">0</div>
                <div class="stat-label">总数</div>
            </div>
        </div>
        
        <!-- 控制栏 -->
        <div class="controls-bar">
            <button class="control-btn open-all-btn" onclick="openAllDoors()">
                🔓 一键开启所有柜门
            </button>
            <button class="control-btn clear-all-btn" onclick="clearAllDoors()">
                🧹 一键清空所有柜门
            </button>
            <button class="control-btn refresh-btn" onclick="loadDoors()">
                🔄 刷新数据
            </button>
            <select class="filter-select" id="statusFilter" onchange="filterDoors()">
                <option value="all">显示全部</option>
                <option value="0">仅可用</option>
                <option value="1">仅已用</option>
                <option value="2">仅开启</option>
            </select>
        </div>
        
        <!-- 柜门网格 -->
        <div id="doorGrid" class="door-grid">
            <div class="loading">正在加载柜门数据...</div>
        </div>
        
        <!-- 命令日志 -->
        <div class="command-log">
            <h3>🔧 MQTT命令日志</h3>
            <div id="commandLog">
                <div class="command-item">
                    <span class="command-time">[等待命令...]</span>
                    <span>系统就绪，通过heart主题发送柜门操作命令</span>
                </div>
            </div>
        </div>
    </div>

    <script>
        let doors = [];
        let deviceName = 'HarmonyOS设备1';
        
        // 获取设备名称
        function getDeviceName() {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get('device') || 'HarmonyOS设备1';
        }
        
        // 初始化页面
        function initPage() {
            deviceName = getDeviceName();
            document.getElementById('deviceName').textContent = `${deviceName} - 实时控制`;
            document.title = `柜门管理 - ${deviceName}`;
            loadDoors();
        }
        
        // 加载柜门数据
        async function loadDoors() {
            try {
                const response = await fetch('/api/boxes');
                doors = await response.json();
                updateStats();
                renderDoors();
            } catch (error) {
                console.error('加载柜门数据失败:', error);
                document.getElementById('doorGrid').innerHTML = 
                    '<div class="loading">加载失败，请检查服务器连接</div>';
            }
        }
        
        // 更新统计信息
        function updateStats() {
            const available = doors.filter(d => d.status === 0).length;
            const occupied = doors.filter(d => d.status === 1).length;
            const open = doors.filter(d => d.status === 2).length;
            const total = doors.length;
            
            document.getElementById('availableCount').textContent = available;
            document.getElementById('occupiedCount').textContent = occupied;
            document.getElementById('openCount').textContent = open;
            document.getElementById('totalCount').textContent = total;
        }
        
        // 渲染柜门
        function renderDoors() {
            const filter = document.getElementById('statusFilter').value;
            let filteredDoors = doors;
            
            if (filter !== 'all') {
                filteredDoors = doors.filter(door => door.status == filter);
            }
            
            const doorGrid = document.getElementById('doorGrid');
            
            if (filteredDoors.length === 0) {
                doorGrid.innerHTML = '<div class="loading">没有找到匹配的柜门</div>';
                return;
            }
            
            doorGrid.innerHTML = filteredDoors.map(door => {
                const statusText = getStatusText(door.status);
                const statusClass = getStatusClass(door.status);
                
                return `
                    <div class="door-card ${statusClass}">
                        <div class="door-header">
                            <div class="door-number">柜门 ${door.boxId}</div>
                            <div class="door-status ${statusClass}">${statusText}</div>
                        </div>
                        
                        <div class="door-info">
                            <div class="door-info-item">
                                <span class="door-info-label">尺寸:</span>
                                <span class="door-info-value">${door.size}</span>
                            </div>
                            <div class="door-info-item">
                                <span class="door-info-label">锁板:</span>
                                <span class="door-info-value">${door.lockBoard}</span>
                            </div>
                            <div class="door-info-item">
                                <span class="door-info-label">锁号:</span>
                                <span class="door-info-value">${door.lockNumber}</span>
                            </div>
                            ${door.phone ? `
                                <div class="door-info-item">
                                    <span class="door-info-label">手机:</span>
                                    <span class="door-info-value">${door.phone}</span>
                                </div>
                            ` : ''}
                        </div>
                        
                        <div class="door-actions">
                            <button class="action-btn open-btn" onclick="openDoor(${door.id}, '${door.boxId}', ${door.lockNumber})">
                                🔓 开启
                            </button>
                            <button class="action-btn clear-btn" onclick="clearDoor(${door.id}, '${door.boxId}')">
                                🧹 清空
                            </button>
                            <button class="action-btn edit-btn" onclick="editDoor(${door.id})">
                                ✏️ 编辑
                            </button>
                        </div>
                    </div>
                `;
            }).join('');
        }
        
        // 获取状态文本
        function getStatusText(status) {
            switch(status) {
                case 0: return '可用';
                case 1: return '已用';
                case 2: return '开启';
                default: return '未知';
            }
        }
        
        // 获取状态样式类
        function getStatusClass(status) {
            switch(status) {
                case 0: return 'status-available';
                case 1: return 'status-occupied';
                case 2: return 'status-open';
                default: return 'status-available';
            }
        }
        
        // 开启单个柜门
        async function openDoor(doorId, boxId, lockNumber) {
            try {
                addCommandLog(`开启柜门 ${boxId} (锁号: ${lockNumber})`);
                
                // 发送MQTT命令到设备 - 使用设备期望的ControlMessage格式
                const command = {
                    command: {
                        action: "OPEN_DOOR",     // 开门动作
                        boxId: boxId,    // 柜子ID
                        lockNumber: lockNumber, // 锁编号
                        doorId: doorId      // 门ID
                    },
                    timestamp: new Date().toISOString(),
                    target_device: deviceName, // 目标设备
                    testMode: true     // Web界面开锁默认为测试模式
                };
                
                const response = await fetch('/api/publish', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        topic: 'cabinet/control/commands',  // 使用新的控制指令主题
                        payload: command
                    })
                });
                
                if (response.ok) {
                    addCommandLog(`✅ 开门命令已发送: 柜门${boxId}`);
                    
                    // 模拟更新本地状态（实际应该等待设备响应）
                    setTimeout(() => {
                        updateDoorStatus(doorId, 2);
                        addCommandLog(`📝 柜门${boxId}状态更新为开启`);
                    }, 1000);
                    
                } else {
                    throw new Error('命令发送失败');
                }
                
            } catch (error) {
                console.error('开启柜门失败:', error);
                addCommandLog(`❌ 开门失败: ${error.message}`);
                alert(`开启柜门${boxId}失败: ${error.message}`);
            }
        }
        
        // 清空单个柜门
        async function clearDoor(doorId, boxId) {
            try {
                addCommandLog(`清空柜门 ${boxId}`);
                
                // 发送MQTT命令到设备 - 使用设备期望的ControlMessage格式
                const command = {
                    command: {
                        action: "CLEAR_DOOR",     // 清空动作
                        boxId: boxId,    // 柜子ID
                        doorId: doorId      // 门ID
                    },
                    timestamp: new Date().toISOString(),
                    target_device: deviceName, // 目标设备
                    testMode: false     // 清空操作不是测试模式
                };
                
                const response = await fetch('/api/publish', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        topic: 'cabinet/control/commands',  // 使用新的控制指令主题
                        payload: command
                    })
                });
                
                if (response.ok) {
                    addCommandLog(`✅ 清空命令已发送: 柜门${boxId}`);
                    
                    // 模拟更新本地状态
                    setTimeout(() => {
                        updateDoorStatus(doorId, 0);
                        addCommandLog(`📝 柜门${boxId}状态更新为可用`);
                    }, 1000);
                    
                } else {
                    throw new Error('命令发送失败');
                }
                
            } catch (error) {
                console.error('清空柜门失败:', error);
                addCommandLog(`❌ 清空失败: ${error.message}`);
                alert(`清空柜门${boxId}失败: ${error.message}`);
            }
        }
        
        // 一键开启所有柜门
        async function openAllDoors() {
            if (!confirm('确定要开启所有柜门吗？此操作不可撤销！')) {
                return;
            }
            
            try {
                addCommandLog(`🔓 执行一键开启所有柜门`);
                
                const command = {
                    command: {
                        action: "OPEN_ALL_DOORS"  // 一键开启所有门动作
                    },
                    timestamp: new Date().toISOString(),
                    target_device: deviceName, // 目标设备
                    testMode: true     // 批量开启为测试模式
                };
                
                const response = await fetch('/api/publish', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        topic: 'cabinet/control/commands',  // 使用新的控制指令主题
                        payload: command
                    })
                });
                
                if (response.ok) {
                    addCommandLog(`✅ 一键开启命令已发送`);
                    
                    // 模拟更新所有柜门状态
                    setTimeout(() => {
                        doors.forEach(door => {
                            updateDoorStatus(door.id, 2);
                        });
                        addCommandLog(`📝 所有柜门状态已更新为开启`);
                    }, 2000);
                    
                } else {
                    throw new Error('命令发送失败');
                }
                
            } catch (error) {
                console.error('一键开启失败:', error);
                addCommandLog(`❌ 一键开启失败: ${error.message}`);
                alert(`一键开启失败: ${error.message}`);
            }
        }
        
        // 一键清空所有柜门
        async function clearAllDoors() {
            if (!confirm('确定要清空所有柜门吗？此操作将清除所有柜门的使用状态！')) {
                return;
            }
            
            try {
                addCommandLog(`🧹 执行一键清空所有柜门`);
                
                const command = {
                    command: {
                        action: "CLEAR_ALL_DOORS"  // 一键清空所有门动作
                    },
                    timestamp: new Date().toISOString(),
                    target_device: deviceName, // 目标设备
                    testMode: false     // 批量清空不是测试模式
                };
                
                const response = await fetch('/api/publish', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        topic: 'cabinet/control/commands',  // 使用新的控制指令主题
                        payload: command
                    })
                });
                
                if (response.ok) {
                    addCommandLog(`✅ 一键清空命令已发送`);
                    
                    // 模拟更新所有柜门状态
                    setTimeout(() => {
                        doors.forEach(door => {
                            updateDoorStatus(door.id, 0);
                        });
                        addCommandLog(`📝 所有柜门状态已更新为可用`);
                    }, 2000);
                    
                } else {
                    throw new Error('命令发送失败');
                }
                
            } catch (error) {
                console.error('一键清空失败:', error);
                addCommandLog(`❌ 一键清空失败: ${error.message}`);
                alert(`一键清空失败: ${error.message}`);
            }
        }
        
        // 编辑柜门
        function editDoor(doorId) {
            const door = doors.find(d => d.id === doorId);
            if (door) {
                alert(`编辑柜门功能开发中...\n\n柜门信息:\n• ID: ${door.id}\n• 柜门号: ${door.boxId}\n• 尺寸: ${door.size}\n• 锁号: ${door.lockNumber}`);
            }
        }
        
        // 更新柜门状态
        function updateDoorStatus(doorId, newStatus) {
            const doorIndex = doors.findIndex(d => d.id === doorId);
            if (doorIndex !== -1) {
                doors[doorIndex].status = newStatus;
                updateStats();
                renderDoors();
            }
        }
        
        // 筛选柜门
        function filterDoors() {
            renderDoors();
        }
        
        // 添加命令日志
        function addCommandLog(message) {
            const commandLog = document.getElementById('commandLog');
            const time = new Date().toLocaleTimeString();
            const logItem = document.createElement('div');
            logItem.className = 'command-item';
            logItem.innerHTML = `
                <span class="command-time">[${time}]</span>
                <span>${message}</span>
            `;
            
            commandLog.insertBefore(logItem, commandLog.firstChild);
            
            // 限制日志数量
            if (commandLog.children.length > 50) {
                commandLog.removeChild(commandLog.lastChild);
            }
        }
        
        // 返回设备管理
        function goBack() {
            const deviceName = getDeviceName();
            window.location.href = `/device-management.html?device=${encodeURIComponent(deviceName)}`;
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initPage();
            
            // 定期刷新数据
            setInterval(loadDoors, 30000); // 每30秒刷新一次
        });
    </script>
</body>
</html>